﻿using System;
using System.Text;

namespace EasyIot.Common
{
    public class CommonUtility
    { 
        /// <summary>
        /// 表示全局唯一标识符 (GUID)。
        /// </summary>
        /// <returns></returns>
        public static string GuId()
        {
            return Guid.NewGuid().ToString();
        }
        /// <summary>
        /// 自动生成编号  201008251145409865
        /// </summary>
        /// <returns></returns>
        public static string CreateNo()
        {
            Random random = new Random();
            string strRandom = random.Next(1000, 10000).ToString(); //生成编号 
            string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
            return code;
        }

        static object ObjLock = new object();
        static DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        /// <summary>
        ///生成制定位数的随机码（数字）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateRandomCode(int Length)
        {
            string result = "";
            int[] Pattern = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int n = Pattern.Length;
            lock (LockObj)
            {
                ThreadSafeRandom safeRandom = new ThreadSafeRandom();
                for (int i = 0; i < Length; i++)
                {
                    int rnd = safeRandom.Next(0, n);
                    result += Pattern[rnd];
                }
            }
            return result;
        }

        static object LockObj = new object();

        public static string GenerateRandomLetter(int Length)
        {
            string result = "";
            char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            int n = Pattern.Length;
            lock (LockObj)
            {
                ThreadSafeRandom safeRandom = new ThreadSafeRandom();
                for (int i = 0; i < Length; i++)
                {
                    int rnd = safeRandom.Next(0, n);
                    result += Pattern[rnd];
                }
            }
            return result;
        }

        public static int String2Int(string sVal)
        {
            int ret = -1;
            try
            {
                ret = Convert.ToInt32(sVal);
            }
            catch (Exception ex)
            {
                Logger.Error("Error:String2Int,errmsg=" + ex.Message + ",val=" + sVal);
            }
            return ret;
        }

        /// <summary>
        /// 将byte[]转换为相对应的字符串,0xae00cf => "AE00CF"
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes, int length, bool space)
        {
            string strFill = space ? " " : "";
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < length; i++)
                {
                    strB.Append(bytes[i].ToString("X2") + strFill);
                }
                hexString = strB.ToString();
            }

            hexString = hexString.Trim();

            return hexString;
        }

        public static string SetData(int iVal, int iPadLen)
        {
            return iVal.ToString().PadLeft(iPadLen, '0');
        } 
        
        /// <summary>
        /// 字节数组转字符串
        /// </summary>
        /// <param name="_byValue"></param>
        /// <returns></returns>
        public static string ByteToString(byte[] _byValue)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            string sResult = Encoding.GetEncoding("GB2312").GetString(_byValue).Replace("\0", string.Empty).Trim();
            return sResult;
        } 

        /// <summary>
        ///生成制定位数的随机码（数字）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateRandomCode()
        {
            var result = new StringBuilder();
            for (var i = 0; i < 6; i++)
            {
                var r = new Random(Guid.NewGuid().GetHashCode());
                result.Append(r.Next(0, 10));
            }
            return result.ToString();
        }

        public static int GetTimestamp(DateTime time)
        {
            int ret = 0;
            lock (ObjLock)
            {
                ret = (int)(time - dtStart).TotalSeconds;
            }
            return ret;
        }

        /// <summary>
        /// 时间戳
        /// </summary>
        /// <returns></returns>
        public static int GetNowTimestamp()
        {
            int ret = 0;
            lock (ObjLock)
            {
                ret = (int)(DateTime.Now - dtStart).TotalSeconds;
            }
            return ret;
        }

        public static int CInts(object _obj)
        {
            int ret = 0;
            try
            {
                ret = Convert.ToInt32(_obj);
            }
            catch (Exception ex)
            {
                Logger.Error("CInts,errmsg:" + ex.Message);
            }
            return ret;
        }

        public static long CBigInts(object _obj)
        {
            long ret = 0;
            try
            {
                ret = Convert.ToInt64(_obj);
            }
            catch (Exception ex)
            {
                Logger.Error("CBigInts,errmsg:" + ex.Message);
            }
            return ret;
        }

        /// <summary>
        /// 防止数据库查询出的数据为DBNull
        /// </summary>
        /// <param name="_obj"></param>
        /// <returns></returns>
        public static int CIntsDB(object _obj)
        {
            int iResult = 0;
            if (!Convert.IsDBNull(_obj))
            {
                iResult = CInts(_obj);
            }
            return iResult;
        }

        public static double CDoubleDB(object _obj)
        {
            double iResult = 0;
            if (!Convert.IsDBNull(_obj))
            {
                try
                {
                    iResult = Convert.ToDouble(_obj);
                }
                catch (Exception ex)
                {

                }
            }
            return iResult;
        }

        /// <summary>
        /// 防止出现Null
        /// </summary>
        /// <param name="_obj">需要处理的对象</param>
        /// <returns>返回字符串</returns>
        public static string CStrs(object _obj)
        {
            return (_obj + "").ToString();
        }

        /// <summary>
        /// 防止数据库查询出的数据为DBNull
        /// </summary>
        /// <param name="_obj">需要处理的对象</param>
        /// <returns>返回字符串</returns>
        public static string CStrsDB(object _obj)
        {
            string sResult = string.Empty;
            if (!Convert.IsDBNull(_obj))
            {
                sResult = CStrs(_obj);
            }
            return sResult;
        }

        public static string Lpad(int iVal, int iPadLen)
        {
            return iVal.ToString().PadLeft(iPadLen, '0');
        }

        public static int GetLength(string str)
        {
            if (str == null || str.Length == 0) { return 0; }

            int l = str.Length;
            int realLen = l;

            int clen = 0;//当前长度
            while (clen < l)
            {
                //每遇到一个中文，则将实际长度加一。
                if ((int)str[clen] > 128) { realLen++; }
                clen++;
            }

            return realLen;
        }
    }
}
